<?php
require_once 'BaseController.php';
require_once APPLICATION_PATH.'/models/Plate.php';
require_once APPLICATION_PATH.'/models/Cate.php';

class PlateController extends BaseController{

    public function plateAction(){
        $tblnav = new Plate();
        $this->view->plates = $tblnav->getPlates();
        $this->view->tblcate = new Cate();
    }

    public function editplateAction(){
        $id = $this->getCheckedId();
        $tblplate = new Plate();
        $tblcate = new Cate();
        $this->view->cates = $tblcate->getCates();
        $this->view->plate = $tblplate->getPlateById($id);
        $this->view->title = '修改板块';
        if($this->view->plate == null){
            //没有找到
            header('Location:'.ADMIN_PATH.'/Plate/plate');
            exit;
        }
        $this->view->act = 'edit';
    }

    public function addplateAction(){
        $tblcate = new Cate();
        $this->view->cates = $tblcate->getCates();
        $this->view->plate = Array(
            'id' => '',
            'name' => '',
            'order' => '',
            'cate1' => '',
            'cate2' => '',
            'cate3' => '',
        );
        $this->view->act = 'add';
        $this->view->title = '新增板块';
        $this->render('editplate');
    }

    public function delplateAction(){
        $id = $this->getCheckedId();
        $tblplate = new Plate();
        if($tblplate->deletePlate($id)<1){
            //删除失败
        }else {
            //删除成功
        }
        header('Location:'.ADMIN_PATH.'/Plate/plate');
        exit;
    }

    public function doupdateAction(){
        $act = $this->_getParam('act');
        $tblplate = new Plate();
        $set = Array(
            'name' => $this->_getParam('name'),
            'order' => $this->_getParam('order'),
            'cate1' => $this->_getParam('cate1'),
            'cate2' => $this->_getParam('cate2'),
            'cate3' => $this->_getParam('cate3'),
        );

        if($act == 'edit'){
            $id = $this->getCheckedId();
            $affected = $tblplate->updatePlate($id, $set);
            if($affected == 0){
                echo '更新无效：您没有对内容进行任何更改！';
            }else if($affected == 1){
                echo '更新成功！';
            }else{
                echo '更新失败！请认真检查您所填写的内容！';
            }
        }
        else if($act == 'add'){
            if($tblplate->addPlate($set)<1){
                //添加失败
            }else {
                //添加成功
            }
        }
        else{}
        header('Location:'.ADMIN_PATH.'/Plate/plate');
        exit;
    }

    private function getCheckedId(){
        $id = $this->_getParam('id');
        if(!is_numeric($id)){
            //参数不合法
            header('Location:'.ADMIN_PATH.'/Plate/plate');
            exit;
        }
        return $id;
    }
}
